package com.jboltai.scheduler;

import com.jboltai.capability.text.TextEventProcessor;
import com.jboltai.config.JBoltAIConfig;
import com.jboltai.event.EventErrorType;
import com.jboltai.event.EventState;
import com.jboltai.event.text.TextEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Iterator;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

class TextEventScheduler extends Scheduler<TextEvent> {


    private static final Logger LOGGER = LoggerFactory.getLogger(JBoltAIConfig.LOGGER_NAME);


    /**
     * 事件队列
     */
    private final LinkedBlockingQueue<TextEvent> eventQueue = new LinkedBlockingQueue(JBoltAIConfig.getMaxTextEventWaitCount());
    private ThreadPoolExecutor EXECUTOR_SERVICE = new ThreadPoolExecutor(JBoltAIConfig.getMaxTextEventThreadCount(), JBoltAIConfig.getMaxTextEventThreadCount(),
            60L, TimeUnit.SECONDS,
            new LinkedBlockingQueue<Runnable>());


    public TextEventScheduler() {
        super("text");
        EXECUTOR_SERVICE.allowCoreThreadTimeOut(true);
    }


    @Override
    void publish(TextEvent event) {
        event.setState(EventState.WAITING);
        try {
            boolean success = eventQueue.offer(event);
            if (!success) {
                event.fail(EventErrorType.QUEUE_FULL);
            }
        } catch (RejectedExecutionException e) {
            //队列满了，不能进了
            event.fail(EventErrorType.QUEUE_FULL);
        }
    }

    @Override
    void process() {
        try {
            //检测该模型的事件队列 是不是空的
//                if (eventQueue.isEmpty()) {
//                    sleep(20);
//                    continue;
//                }


            Iterator<TextEvent> iterator = eventQueue.iterator();
            while (iterator.hasNext()) {
                TextEvent event = iterator.next();

                dispatch(event);

                if (event.getState() != EventState.WAITING) {
                    //不是等待状态，就不用再处理了
                    iterator.remove();
                }
            }
//                sleep(10);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }


    }

    @Override
    void dispatch(TextEvent event) {

        if (EXECUTOR_SERVICE.getActiveCount() < EXECUTOR_SERVICE.getCorePoolSize()) {
            if (event.setState(EventState.PROCESSING)) {

                EXECUTOR_SERVICE.execute(new TextEventProcessor(event));
            }
            return;
        }

        if (event.getWaitTimestamp() > 0 && System.currentTimeMillis() > event.getWaitTimestamp()) {
            //超时了就算了
            event.fail(EventErrorType.QUEUE_WAIT_TIMEOUT);
            LOGGER.error("事件{} 等待超时，放弃执行", event.getId());
            return;
        }
        if (event.getState() != EventState.WAITING) {
            //不是等待状态，肯定不在等待队列中了,是要立马执行的
            new Thread(new TextEventProcessor(event)).start();
        }
    }
}
